package cn.itsource.config.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.PetConstant;
import cn.itsource.basic.util.RedisService;
import cn.itsource.org.Vo.LoginVo;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录拦截器
 */
@Component //交给Spring管理
public class LoginInterceptor implements HandlerInterceptor {
//    注入redis组件
    @Autowired
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        告知浏览器的解析格式
        response.setContentType("application/json;charset=utf-8");
//        从reques获取token信息
        String token = request.getHeader("token");
//        如果token不存在就重新登录
        if (StrUtil.isBlank(token)){
            return extracted(response);
        }
//        拿到token,从redis中获取登录信息
        LoginVo vo = redisService.getKeyObjectValue(token, LoginVo.class);
//        如果没有获取到,就重新登录
        if (vo==null){
            return extracted(response);
        }
//        最后要刷新redis的登录信息,以及时间
        redisService.setStringKeyAndValue(token,vo,30);
        return true;
    }

    private boolean extracted(HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        //1001
        AjaxResult loginResult = AjaxResult.createError(PetConstant.SYSTEM_LOGIN_TIMOUT);
        writer.write(JSONObject.toJSONString(loginResult));
        //拦截
        return false;
    }
}
